#include "acbookmain.h"
#include "ui_acbookmain.h"

#include <QMessageBox>
#include <QStandardItemModel>
#include <QScrollBar>

#include "ItemOperator/itemoperatordelegate.h"
#include "ItemOperator/itembutton.h"
#include "dialog/itemeditor.h"
#include "fixedfield/fixedfield.h"
#include "FlowLayout/flowlayout.h"

AcBookMain::AcBookMain(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::AcBookMain)
{
    m_db = new AcDB();
    if (!m_db->open())
    {
        return;
    }

    ui->setupUi(this);
    ui->newItemName->setFocus();

    QStringList dayHeadLabels;
    QStandardItemModel* dayModel = new QStandardItemModel(1, 5);
    dayHeadLabels << tr("名称") << tr("类型") << tr("金额") << tr("操作");
    dayModel->setHorizontalHeaderLabels(dayHeadLabels);

    ui->dayTableView->setSortingEnabled(true);
    ui->dayTableView->setModel(dayModel);
    ui->dayTableView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
    ui->dayTableView->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->dayTableView->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);
    ui->dayTableView->horizontalHeader()->setResizeMode(3, QHeaderView::Fixed);
    ui->dayTableView->setItemDelegateForColumn(3, new ItemOperatorDelegate());
    ui->dayTableView->hideColumn(4);

    m_db->listClass(&typeSelections);
    for (int i = 0; i < typeSelections.size(); i++)
    {
        ui->newItemClass->addItem(typeSelections.at(i).at(1).toString());
    }

    FlowLayout *flowLayout = new FlowLayout;

//    flowLayout->addWidget(new QPushButton(tr("Short")));
//    flowLayout->addWidget(new QPushButton(tr("Longer")));
//    flowLayout->addWidget(new QPushButton(tr("Different text")));
//    flowLayout->addWidget(new QPushButton(tr("More text")));
//    flowLayout->addWidget(new QPushButton(tr("Even longer button text")));
    ui->fixedItemAreaChild->setLayout(flowLayout);

    //QGridLayout* layout = (QGridLayout*)ui->fixedItemArea->layout();
    //FixedField* field = new FixedField();
    //layout->addWidget(new FixedField(), 0, 0);
    //layout->addWidget(new FixedField(), 0, 1);

    m_db->getFixedItemList(flowLayout);

    // 设置到今天
    on_newItemCalendar_selectionChanged();
}

AcBookMain::~AcBookMain()
{
    delete ui;
    delete m_db;
}

void AcBookMain::on_clear_ToolbarButton(QWidget* checked)
{
    int pageCount = ui->toolBox->count();
    for (int i = 0; i < pageCount; i++)
    {
        QObjectList buttonlist = ui->toolBox->widget(i)->children();

        foreach (QObject* objMain, buttonlist)
        {
            QPushButton* bt = (QPushButton*)objMain;
            if (bt->objectName().endsWith("Bt"))
                bt->setChecked(false);
        }
    }

    ((QPushButton*)checked)->setChecked(true);
}

void AcBookMain::on_viewNewItemBt_clicked()
{
    ui->acbookStack->setCurrentIndex(0);
    on_clear_ToolbarButton(ui->viewNewItemBt);
}

void AcBookMain::on_viewItemSearchBt_clicked()
{
    ui->acbookStack->setCurrentIndex(1);
    on_clear_ToolbarButton(ui->viewItemSearchBt);
}

void AcBookMain::on_viewIoStatistictBt_clicked()
{
    ui->acbookStack->setCurrentIndex(2);
    on_clear_ToolbarButton(ui->viewIoStatistictBt);
}

void AcBookMain::on_viewFinancialReportBt_clicked()
{
    ui->acbookStack->setCurrentIndex(3);
    on_clear_ToolbarButton(ui->viewFinancialReportBt);
}

void AcBookMain::on_viewAssetsBt_clicked()
{
    ui->acbookStack->setCurrentIndex(4);
    on_clear_ToolbarButton(ui->viewAssetsBt);
}

void AcBookMain::on_viewExImportBt_clicked()
{

}

void AcBookMain::on_viewSelectedItemsBt_clicked()
{

}

void AcBookMain::on_viewConfigrationBt_clicked()
{

}

void AcBookMain::on_viewCalcMortgageBt_clicked()
{

}

void AcBookMain::on_viewCalcSiBt_clicked()
{

}

void AcBookMain::on_todayButton_clicked()
{
    ui->newItemCalendar->setSelectedDate(QDate::currentDate());
}

void AcBookMain::on_newItemCalendar_selectionChanged()
{
    ui->selectedDateBox->setTitle(tr("选择日期：").append(ui->newItemCalendar->selectedDate().toString("yyyy-MM-dd")));

    QList<float> dioResult;
    if (m_db->getDayBrief(ui->newItemCalendar->selectedDate(), &dioResult))
        ui->todayInOutcome->setText(tr("本日收入：%1  本日消费：%2").arg(dioResult[0], 0, 'f', 2).arg(dioResult[1], 0, 'f', 2));

    QList<float> mioResult;
    if (m_db->getMonthBrief(ui->newItemCalendar->selectedDate(), &mioResult))
    {
        ui->monthIncome->setText(QString("%1").arg(mioResult[0], 0, 'f', 2));
        ui->monthOutcome->setText(QString("%1").arg(mioResult[1], 0, 'f', 2));
        ui->monthRemain->setText(QString("%1").arg(mioResult[2], 0, 'f', 2));
        ui->lastMonthRemain->setText(QString("%1").arg(mioResult[3], 0, 'f', 2));
        ui->totalRemain->setText(QString("%1").arg(mioResult[4], 0, 'f', 2));
    }

    QList<float> salaryResult;
    if (m_db->getMonthSalary(ui->newItemCalendar->selectedDate(), &salaryResult))
    {
        ui->maleSalary->setText(QString("%1").arg(salaryResult[0], 0, 'f', 2));
        ui->femaleSalary->setText(QString("%1").arg(salaryResult[1], 0, 'f', 2));
    }

    m_db->getDayDataset(ui->newItemCalendar->selectedDate(), ui->dayTableView->model());
    for (int i = 0; i < ui->dayTableView->model()->rowCount(); ++i)
    {
        ui->dayTableView->openPersistentEditor( ui->dayTableView->model()->index(i, 3, QModelIndex()) );
    }
}

void AcBookMain::onItemModify()
{
    ItemButton *editor = static_cast<ItemButton *>(sender());
    ItemEditor dlg(editor->id, m_db);
    if (dlg.exec() == 1)
    {
        on_newItemCalendar_selectionChanged();
    }
}

void AcBookMain::onItemDelete()
{
    QMessageBox msg;
    msg.setText(tr("即将删除记录。"));
    msg.setInformativeText(tr("确定要删除吗？"));
    msg.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg.setDefaultButton(QMessageBox::Yes);
    if (msg.exec() == QMessageBox::Yes)
    {
        ItemButton *editor = static_cast<ItemButton *>(sender());
        if (m_db->delItem(editor->id))
            on_newItemCalendar_selectionChanged();
    }
}

void AcBookMain::on_newItemCancelButton_clicked()
{
    ui->newItemName->setText("");
    ui->newItemCost->setValue(0);
    ui->newItemClass->setCurrentIndex(0);
    ui->newItemName->setFocus();
}

void AcBookMain::on_newItemAddButton_clicked()
{
    QList<QVariant> data;
    data.append(ui->newItemName->text());
    data.append(typeSelections.at(ui->newItemClass->currentIndex()).at(0).toInt());
    data.append(ui->newItemCalendar->selectedDate());
    data.append(ui->newItemCost->value());
    if (m_db->addItem(&data))
    {
        on_newItemCalendar_selectionChanged();
    } else {
        QMessageBox::warning(NULL, "输入错误", "无法插入数据");
    }
}

void AcBookMain::on_maleSalary_editingFinished()
{
    if (ui->maleSalary->isModified())
    {
        QDate date = ui->newItemCalendar->selectedDate();
        if (m_db->updateSalary(&date, ui->maleSalary->text().toFloat(), 1))
        {
            on_newItemCalendar_selectionChanged();
        }
    }
}


void AcBookMain::on_femaleSalary_editingFinished()
{
    if (ui->femaleSalary->isModified())
    {
        QDate date = ui->newItemCalendar->selectedDate();
        if (m_db->updateSalary(&date, ui->femaleSalary->text().toFloat(), 2))
        {
            on_newItemCalendar_selectionChanged();
        }
    }
}
